!function () {
    layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat','upload', 'form','status','common'], function () {
        //定义
        var $ = layui.jquery,
            table = layui.table,
            form = layui.form,
            upload = layui.upload,
            dateformat = layui.dateformat,
            laydate = layui.laydate,
            layuiSta = layui.status,//自定义状态控件
            common = layui.common;//自定义状态控件

        //定义总变量
        var Banner = {
            tableId: "bannerTable",    //表格id
            condition: {                //查询条件
                bannerName: "",
                bannerType: "",
                startDate: "",
                endDate: ""
            }
        }
        //定义所属类别
        var bannerType ={
            "1":"首页Banner轮播图",
            /*"2":"产品展示页Banner图",
            "3":"人才合作页Banner图",*/
            "4":"官网导航栏图片",
            "5":"官网广告图片",
            "6":"门店版图轮播图"
        }

        //定义所属位置
        var positionType ={
            "1":{"1":"官网首页"},
            /*"2":{"2":"产品展示页"},
            "3":{"3":"人才合作页"},*/
            "4":{"4":"品牌二级导航栏","5":"产品二级导航栏","6":"合作二级导航栏","7":"资讯二级导航栏","8":"会员二级导航栏"},
            "5":{"51":"广告图片一","52":"广告图片二","53":"广告图片三","54":"广告图片四","55":"广告图片五","56":"广告图片六"},
            "6":{"61":"门店版图轮播图"}
        }

        /**
         * 初始化列表列
         * **/
        Banner.initColumn = function(){
            return [[
                /*{type: 'checkbox', fixed: 'left'},*/
                {field: 'bannerId', title: 'ID', width: 80,hide:true},
                {field: 'bannerName', title: '轮播图名称', width: 160},
                {field: 'bannerUrl', title: '轮播图', width: 260,templet: '#imgRender'},
                {field: 'bannerType' ,title :'所属类别',width:180,templet:function(row){
                    return bannerType[row.bannerType];
                    }},
                {field: 'bannerPosition' ,title :'轮播图位置',width:180,templet:function(row){
                        return positionType[row.bannerType][row.bannerPosition];
                    }},
                {field: 'sort' ,title :'排序',width:120},
                {field: 'status' ,title :'显示',width:120,templet:'#statusClo'},
                {field: 'createTime' ,title :'创建时间',width: 165, templet: function (row) {
                        return dateformat.format(common.NewDate(row.createTime), 'yyyy-MM-dd hh:mm:ss');
                    }},
                {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 180, align: 'center'}
            ]];
        }

        /**
         * 查询方法
         * **/
        Banner.search = function(){
            var queryData = {};
            queryData["bannerName"] = $("#bannerName").val();
            queryData["bannerType"] = $("#bannerType").val();
            queryData["startDate"] = $("#startDate").val();
            queryData["endDate"] = $("#endDate").val();
            table.reload(Banner.tableId, {where: queryData,page: {curr: 1}});
        }

        /**
         * 查询条件渲染
         * @param typeId
         */
        Banner.initQueryType  = function( typeId ){
            var $select = $(typeId);
            $select.empty().append('<option value="">请选择</option>');
            for (var i in bannerType) {
                $select.append('<option value="'+i+'">' + bannerType[i] + '</option>');
            }
            layui.form.render('select');
        }

        /***
         * 初始化联动下拉
         */
        Banner.initTypeSelect = function(typeId,positionId,type,position){

            var $selectChild = $(positionId),$selectParent = $(typeId);
            //加载一级下拉框选项
            $selectParent.empty().append('<option value="">请选择</option>');
            for (var i in bannerType) {
                if( i == type ){
                    $selectParent.append('<option value="'+i+'" selected>' + bannerType[i] + '</option>');
                    //构建二级select
                    var s = positionType[type];
                    $selectChild.html('<option value="">请选择</option>');
                    for (var c in s) {
                        if( c == position ){
                            $selectChild.append('<option value="'+c+'" selected>' + s[c] + '</option>');
                        }else{
                            $selectChild.append('<option value="'+c+'">' + s[c] + '</option>');
                        }
                    }
                }else{
                    $selectParent.append('<option value="'+i+'">' + bannerType[i] + '</option>');
                }
            }
            layui.form.render('select');

            //根据省份下拉框值，加载相应的城市下拉框选项，并定位地图中心点
            form.on('select(selVal)',function (data) {
                var s = positionType[data.value];
                $selectChild.html('<option value="">请选择</option>');
                for (var i in s) {
                    $selectChild.append('<option value="'+i+'">' + s[i] + '</option>');
                }
                layui.form.render();
            });

        }

        /**
         * 新增记录
         * **/
        Banner.addRecord =function (){

            //初始化表单
            $('#editForm')[0].reset();
            $('#editForm :input').val("");//重置所有的input
            $('#uploadListDiv').empty();
            Banner.initTypeSelect('#editForm [name=bannerType]','#editForm [name=bannerPosition]');
            layuiSta.initSta("#statusDiv",'',true);//构建状态
            $('#editForm [name=bannerType]').removeAttr("disabled");
            $('#editForm [name=bannerPosition]').removeAttr("disabled");
            layui.form.render();
            //打开弹出层
            layer.open({
                type: 1, maxmin: true, title: '新增轮播图', shade: 0.4, shadeClose: false,
                area: ['452px', '700px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                yes: function () {
                    $('#saveRecord').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#editForm').hide();
                }
            });
        }

        /**
         * 修改记录
         * **/
        Banner.editRecord =function (data){
            //初始化数据
            var $uploadListDiv = $('#uploadListDiv');
            var $tipUpload = $('#imgText');
            $('#uploadListDiv').empty();
            $.ajax({
                async: false,
                url: '/banner/findBanner?bannerId=' + data.bannerId,
                success: function (result) {
                    if (result && result.code == 200) {
                        var data = result.data;
                        //初始化表单
                        form.render('radio').val('editForm', data);
                        layuiSta.initSta("#statusDiv",data.status,true);//构建状态
                        Banner.initTypeSelect('#editForm [name=bannerType]','#editForm [name=bannerPosition]',data.bannerType,data.bannerPosition);
                        //修改菜单不可修改所属类型+所在位置
                        $('#editForm [name=bannerType]').attr("disabled","disabled");
                        $('#editForm [name=bannerPosition]').attr("disabled","disabled");
                        //构建图片或者视频
                        var htmlDiv ='';
                        if(data.bannerUrl.indexOf("image") !=-1){
                            htmlDiv +='<img id="fileDiv" src="'+data.bannerUrl+'" style="height: 137px;width: 137px;"/>';
                        }
                        if(data.bannerUrl.indexOf("media") !=-1){
                            htmlDiv +='<video id="fileDiv" src="'+data.bannerUrl+'"  style="height: 137px;width: 137px;"/>';
                        }
                        $uploadListDiv.empty().append(htmlDiv);
                        form.render('select');
                        //打开弹出层
                        layer.open({
                            type: 1, maxmin: true, title: '修改轮播图', shade: 0.4, shadeClose: false,
                            area: ['452px', '700px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                            yes: function () {
                                $('#saveRecord').click();
                            }, btn2: function () {
                                layer.closeAll();
                            }, end: function () {
                                $('#editForm').hide();
                            }
                        });
                    }else
                        layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        /**
         * 删除记录
         * **/
        Banner.deleteRecord =function (data){

            $.ajax({
                async: false,
                type: 'post',
                url: '/banner/delete?bannerId=' + data.bannerId,
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Banner.search();
                    }
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        //日期
        var startDate = laydate.render({
            elem: '#startDate',
            done: function(value, date){
                endDate.config.min = date;
                endDate.config.min.month = date.month -1;
            }
        });
        var endDate =  laydate.render({
            elem: '#endDate',
            done: function(value, date){
                if($.trim(value) == ''){
                    var curDate = new Date();
                    date = {'date': curDate.getDate(), 'month': curDate.getMonth()+1, 'year': curDate.getFullYear()};
                }
                startDate.config.max = date;
                startDate.config.max.month = date.month -1;
            }
        });

        //查询条件下拉渲染
        Banner.initQueryType("#bannerType");
        //渲染上传
        //普通图片上传
        var uploadFileBtn = upload.render({
            elem: '#uploadBtn'
            ,url: '/upload/uploadFiles'
            ,field:"layuiFiles"
            ,accept: 'file' //普通文件
            ,auto: false    //不自动上传
            ,exts: 'jpg|png|jpeg|mp4' //只允许上传压缩文件
            ,choose: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    var $uploadListDiv = $('#uploadListDiv');
                    var $tipUpload = $('#imgText');
                    var htmlDiv ='';
                    if(file.type.indexOf("image") !=-1){
                        if( (file.size/1014).toFixed(1) > 10240 ){
                           return layer.msg("图片不能大于10M");
                        }
                        var positionType = $("select[name=bannerType]").val();//轮播图类型
                        if( positionType == undefined ){
                            layer.msg("请选择对应的轮播图位置");
                            return false;
                        }
                        var bannerPosition = $("select[name=bannerPosition]").val();//轮播图位置
                        //限制图片尺寸
                        var img = new Image();

                        var flagUpload = true;
                        img.onload = function(){
                            if( positionType =="" || positionType ==undefined
                                || bannerPosition =="" || bannerPosition== undefined){
                                layer.msg("请选择对应的轮播图类型与轮播图位置");
                                flagUpload= false;
                            }else{
                                switch (positionType){
                                    case "1":
                                        if(img.width != 1920 || img.height != 780){
                                            layer.msg("首页图片固定尺寸为1920*780");
                                            flagUpload= false;
                                        }
                                        break;
                                    case "2":
                                        if(img.width != 1920 || img.height != 780){
                                            layer.msg("产品展示页图片固定尺寸为1920*780");
                                            flagUpload= false;
                                        }
                                        break;
                                    case "3":
                                        if(img.width != 1920 || img.height != 780){
                                            layer.msg("人才合作页图片固定尺寸为1920*780");
                                            flagUpload= false;
                                        }
                                        break;
                                    case "4":
                                        if(img.width != 238 || img.height != 316){
                                            layer.msg("二级菜单导航图片固定尺寸为238*316");
                                            flagUpload= false;
                                        }
                                        break;
                                    case "5":
                                        if( (bannerPosition == "51" || bannerPosition=="55")){
                                            if(img.width != 948 || img.height != 1081){
                                                layer.msg("广告图片尺寸为948*1081");
                                                flagUpload= false;
                                            }
                                        }else{
                                            if(img.width != 948 || img.height != 664){
                                                layer.msg("广告图片最小尺寸为948*664");
                                                flagUpload= false;
                                            }
                                        }
                                        break;
                                    case "6":
                                        if(img.width != 948 || img.height != 500){
                                            layer.msg("门店版图图片尺寸为948*500");
                                            flagUpload= false;
                                        }
                                        break;
                                }
                            }
                            uploadFileBtn.config.data ={"dir":"image"};
                            htmlDiv +='<img id="fileDiv" style="height: 137px;width: 137px;"/>';
                            if( flagUpload ){
                                $uploadListDiv.empty().append(htmlDiv);
                                //执行上传
                                obj.upload(index, file);
                            }
                        };
                        img.src = result;
                    }
                    if(file.type.indexOf("video") !=-1){
                        if( (file.size/1014) > 153600 ){
                            return layer.msg("视频不能大于150M");
                            return false;
                        }
                        uploadFileBtn.config.data ={"dir":"media"};
                        htmlDiv +='<video id="fileDiv" style="height: 137px;width: 137px;"/>';
                        $uploadListDiv.empty().append(htmlDiv);
                        //执行上传
                        obj.upload(index, file);
                    }
                });
            }
            ,done: function(res){
                if(res.code==1){
                    layer.alert(res.message,5);
                }
                if(res.error>0){
                    return layer.msg(res.message);
                }
                if(res.error==0){
                    var $uploadListDiv = $('#uploadListDiv');
                    $("#bannerUrl").val(res.url);
                    $uploadListDiv.find("#fileDiv").attr("src",res.url);
                    layer.msg("上传成功");
                }
            }
        });

        table.render({
            elem:"#bannerTable"
            ,url:"/banner/listPage"
            ,cellMinWidth:80
            ,request: {pageName: 'pageNum', limitName: 'pageSize'}
            ,page: true
            ,cols:Banner.initColumn(),
            cellMinHeight:200

        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            Banner.search();
        });

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');
            Banner.search();
        });

        // 添加按钮点击事件
        $('#btnAdd').click(function () {
            Banner.addRecord();
        });

        //监听工具条
        table.on('tool(' + Banner.tableId + ')',function(obj){
            var data = obj.data;
            var layEvent = obj.event;
            if( layEvent ==='detail'){
                //查看
                return false;
            } else if( layEvent ==='del'){
                layer.confirm('确定要删除当前轮播图吗', function (index) {
                    Banner.deleteRecord(data);
                    return false;
                });
            } else if( layEvent ==='edit'){
                Banner.editRecord(data);
                return false;
            }
        });

        //监听状态操作
        form.on('switch(setStatus)', function(obj){
            $.ajax({
                async: false,
                type: 'post',
                url: '/banner/setStatus',
                data:{"bannerId":this.value,"status":obj.elem.checked?1:0},
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.tips('修改状态成功', obj.othis);
                    }
                },
                error: function () {
                    layer.alert('修改状态失败', obj.othis);
                }
            });
        });

        //监听提交事件
        form.on('submit(editRecord)',function(data){

            var postUrl = !data.field['bannerId'] ? '/banner/addBanner' : '/banner/editBanner';
            //通过from提交  包含图片
            var formdata  = new FormData(data.form);
            $.ajax({
                async: false, type: 'post', traditional: true, data: formdata, url: postUrl,
                contentType:false,processData:false,
                success: function (data) {
                    if (data && data.code == 200) {
                        layer.closeAll();
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Banner.search();
                    } else
                        layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.closeAll();
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
            return false;
        });

    });
}();